from flask import Blueprint,request,jsonify,redirect
import json,random,time,requests
from models.user import *
from util.myredis import r
from util.comm import get_ali_object

pay_blue = Blueprint("payblue",__name__)



@pay_blue.route("/payurl")
def payurl():
    money = request.args.get("money")
    userid = request.args.get('userid')
    # 生成订单号
    number = str(int(time.time())) + str(userid) + str(random.randint(10000,99999))
    # 加入充值变化表
    ref = refil(number=number, money=money, status=0, userid=userid)
    db.session.add(ref)
    db.session.commit()
    pay_time = int(time.time()) + 30
    # 加入redis
    r.sortedset_add('refil',number,pay_time)
    pay = get_ali_object()
    query_params = pay.direct_pay(
        subject=str(userid) + '充值记录',   # 商品简单描述
        out_trade_no=number,  # 用户购买的商品订单号（每次不一样） 20180301073422891
        total_amount=float(money),  # 交易金额(单位: 元 保留俩位小数)
    )
    pay_url = "https://openapi.alipaydev.com/gateway.do?{0}".format(query_params)  # 支付宝网关地址（沙箱应用）
    return jsonify({
        'code': 200,
        'url': pay_url
    })


# 回调
@pay_blue.route("/callback")
def callback():
    data = request.args
    print(data)
    # 对参数进行处理
    datames = {k: v for k,v in data.items()}
    # 从字典中将sign删除
    sign = datames.pop('sign')
    # 获取支付宝对象
    alipay = get_ali_object()
    # 调用验签
    flag = alipay.verify(datames, sign)
    print(flag)
    if flag == True:
        trade_no = datames['trade_no']
        out_trade_no = datames['out_trade_no']  # 订单号
        ref = refil.query.filter_by(number=out_trade_no).first()
        userid = ref.userid
        print("userid", userid)
        money = ref.money
        users = User.query.filter_by(id=userid).first()
        umoney = users.money
        print('umoney', umoney)
        tmoney = money+umoney  # 当前用户总金额
        print('tmoney', tmoney)
        try:
            User.query.filter_by(id=userid).update({'money': tmoney})
            print(333)
            refil.query.filter_by(number=out_trade_no).update({'status': 1, 'serialnumber': trade_no})
            print(444)
            refils = refil_change(money=money, descs=1, userid=userid)
            db.session.add(refils)
            print(555)
            db.session.commit()
        except:
            return jsonify({'code': 1002, 'msg': '禁止盲目个别更改'})
        return redirect("http://localhost:8080/pay")
    return jsonify({'code': 1001, 'msg': '验签失败'})

def payment():
    data = datetime.datetime.now()-datetime.timedelta(minutes=1)
    now = datetime.datetime.strftime(data, '%Y-%m-%d 00:59:59')
    refils = refil.query.filter_by(status=0).all()
    for i in refils:
        print(i.create_time)
        pay = get_ali_object()
        print(pay)
        query_params = pay.query_pay(
            out_trade_no=i.number
        )
        pay_url = "hettps://openapi.alipaydev.com/gateway.do?{0}".format(query_params)   # 支付宝网关地址（沙箱应用）
        res = requests.get(pay_url)
        print(res.text)
        aa = json.loads(res.text)
        code = aa["alipay_trade_query_response"]['code']
        print(code)
        if int(code) == 40004:
            print(1)
            # if str(i.create_time) < str(now):
            refil.query.filter_by(number=i.number).delete()
            db.session.commit()
            return '交易失效'
        if int(code) == 10000:
            print(2)
            return 'ok'
            # sql = "delete from payrecord where number='%s'"%(i.decode())
            # r.sortedset_delete("numberpay", i.decode())
    else:
        return '没有数据'

@pay_blue.route("/getusermoney")
def getusermoney():
    userid = request.args.get('userid')
    user = User.query.filter_by(id=userid).first()
    print('_____', user)
    money = user.money
    lockmoney = user.lockmoney
    return jsonify({'code': 200, 'money': money, 'lockmoney': lockmoney})




























